package com.fast.cron.common.config;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

import java.io.File;
import java.net.URL;

/**
 * properties file load helper
 *
 * @author :leo.jie
 * @version :v1.0
 * @date :2018/9/29 11:14
 */
public class PropConfigManager {
    private static volatile PropertiesConfiguration prop = null;
    private String configName;

    private PropConfigManager(String configName) throws ConfigurationException {
        this.configName = configName;
        loadConfig();
    }

    private void loadConfig() throws ConfigurationException {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(this.configName);
        if (null == url) {
            throw new RuntimeException("load config file failed,may be the config file is not exists!");
        }
        if (null == prop) {
            prop = new PropertiesConfiguration();
        }
        File file = new File(url.getFile());
        prop.setFile(file);
        prop.setAutoSave(false);
        prop.load();
    }

    public String getProperty(String key) {
        return prop.getString(key);
    }

    public Integer getInteger(String key) {
        String value = getProperty(key);
        return Integer.valueOf(value);
    }

    public Long getLong(String key) {
        String value = getProperty(key);
        return Long.valueOf(value);
    }

    public Boolean getBoolean(String key) {
        String value = getProperty(key);
        return Boolean.valueOf(value);
    }

    private static class PropConfigHolder {
        private static PropConfigManager getInstance(String configName) {
            PropConfigManager instance = null;
            try {
                instance = new PropConfigManager(configName);
            } catch (ConfigurationException e) {
                e.printStackTrace();
            }
            return instance;
        }
    }

    public static PropConfigManager build(String configName) {
        return PropConfigHolder.getInstance(configName);
    }
}
